import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Card, Image, Upload, Modal, Form, Input, Button, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";

import PageHeader from "../components/PageHeader";
import PersonalInfoItem from "../components/PersonalInfoItem";

import { updateUserInfoAsync } from "../redux/userSlice";
import { formatDate } from "../utils/tools";
import { checkPassword } from "../api/user";
import styles from "../css/Personal.module.css";

function Personal() {
  const { userInfo } = useSelector((state) => state.user);
  const dispatch = useDispatch();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [panelName, setPanelName] = useState("");
  const [pwdForm] = Form.useForm();
  const [socialForm] = Form.useForm();
  const [infoForm] = Form.useForm();

  const showModal = (name) => {
    setPanelName(name);
    // 每次打开模态框的时候，清空上一次提交的新内容信息
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    pwdForm.resetFields();
    socialForm.resetFields();
    infoForm.resetFields();
    setIsModalOpen(false);
  };

  const handleSubmit = (value) => {
    // 用户点击了确定按钮，表明要确定修改信息
    // 派发异步 action
    if (value.newpassword) {
      // 修改密码
      dispatch(
        updateUserInfoAsync({
          userId: userInfo._id,
          newInfo: {
            loginPwd: value.newpassword,
          },
        })
      );
    } else {
      dispatch(
        updateUserInfoAsync({
          userId: userInfo._id,
          newInfo: value,
        })
      );
    }
    setIsModalOpen(false);
    message.success("信息修改成功！");
  };

  // 修改头像
  function handleAvatar(newURL, key) {
    // 将仓库和服务器端的数据一起更新
    dispatch(
      updateUserInfoAsync({
        userId: userInfo._id,
        newInfo: {
          [key]: newURL,
        },
      })
    );
    message.success("头像修改成功");
  }

  /**
   * 验证用户输入的旧密码是否正确
   */
  async function checkPasswordIsRight(_, value) {
    if (value) {
      const { data } = await checkPassword(userInfo._id, value);
      if (!data) {
        // 说明密码不正确
        return Promise.reject("密码不正确");
      }
    }
  }

  // 模态框中间显示的内容
  let modalContent = null;
  switch (panelName) {
    case "基本信息": {
      modalContent = (
        <>
          <Form
            name="basic1"
            autoComplete="off"
            form={pwdForm}
            initialValues={{
              oldpassword: "", // 旧密码
              newpassword: "", // 新密码
              passwordConfirm: "", // 确认密码
            }}
            onFinish={handleSubmit}
          >
            {/* 登录密码 */}
            <Form.Item
              label="登录密码"
              name="oldpassword"
              rules={[
                {
                  required: true,
                  message: "请输入登录密码",
                },
                {
                  validator: checkPasswordIsRight,
                },
              ]}
              validateTrigger="onBlur"
            >
              <Input.Password
                rows={6}
                autoComplete="off"
                placeholder="如果要修改密码，请先输入旧密码"
              />
            </Form.Item>

            {/* 新的登录密码 */}
            <Form.Item
              label="新密码"
              name="newpassword"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                },
                {
                  min: 6,
                  message: "密码长度不小于6",
                },
              ]}
              validateTrigger="onBlur"
            >
              <Input.Password
                rows={6}
                autoComplete="off"
                placeholder="请输入新密码"
              />
            </Form.Item>

            {/* 确认密码 */}
            <Form.Item
              label="确认密码"
              name="passwordConfirm"
              rules={[
                {
                  required: true,
                  message: "请输入确认密码",
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("newpassword") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error("两次密码不一致"));
                  },
                }),
              ]}
              validateTrigger="onBlur"
            >
              <Input.Password
                rows={6}
                autoComplete="off"
                placeholder="请确认密码"
              />
            </Form.Item>

            {/* 确认修改按钮 */}
            <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>

              <Button type="link" htmlType="reset" className="resetBtn">
                重置
              </Button>
            </Form.Item>
          </Form>
        </>
      );
      break;
    }
    case "社交账号": {
      modalContent = (
        <>
          <Form
            name="basic2"
            form={socialForm}
            initialValues={{
              mail: userInfo.mail,
              qq: userInfo.qq,
              wechat: userInfo.wechat,
              github: userInfo.github,
            }}
            autoComplete="off"
            onFinish={handleSubmit}
          >
            <Form.Item label="邮箱" name="mail">
              <Input placeholder="请填写邮箱" />
            </Form.Item>
            <Form.Item label="QQ号" name="qq">
              <Input placeholder="请填写 QQ 号" />
            </Form.Item>
            <Form.Item label="微信" name="wechat">
              <Input placeholder="请填写微信号" />
            </Form.Item>
            <Form.Item label="github" name="github">
              <Input placeholder="请填写 github " />
            </Form.Item>

            {/* 确认修改按钮 */}
            <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>

              <Button type="link" htmlType="reset" className="resetBtn">
                重置
              </Button>
            </Form.Item>
          </Form>
        </>
      );
      break;
    }
    case "个人简介": {
      modalContent = (
        <>
          <Form
            name="basic3"
            form={infoForm}
            initialValues={{
              intro: userInfo.intro,
            }}
            autoComplete="off"
            onFinish={handleSubmit}
          >
            {/* 自我介绍 */}
            <Form.Item label="自我介绍" name="intro">
              <Input.TextArea rows={6} placeholder="选填" />
            </Form.Item>

            {/* 确认修改按钮 */}
            <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确认
              </Button>

              <Button type="link" htmlType="reset" className="resetBtn">
                重置
              </Button>
            </Form.Item>
          </Form>
        </>
      );
      break;
    }
  }
  return (
    <div>
      <PageHeader title="个人中心" />
      {/* 信息展示 */}
      <div className={styles.container}>
        {/* 基本信息 */}
        <div className={styles.row}>
          <Card
            title="基本信息"
            extra={
              <div
                className={styles.edit}
                onClick={() => showModal("基本信息")}
              >
                编辑
              </div>
            }
          >
            <PersonalInfoItem
              info={{ itemName: "登录账号", itemValue: userInfo.loginId }}
            />
            <PersonalInfoItem
              info={{ itemName: "账号密码", itemValue: "**** **** ***" }}
            />
            <PersonalInfoItem
              info={{
                itemName: "用户昵称",
                itemValue: userInfo.nickname,
                // 以下是编辑需要额外添加的信息
                itemKey: "nickname",
                userId: userInfo._id,
              }}
              editable={true}
            />
            <PersonalInfoItem
              info={{
                itemName: "用户积分",
                itemValue: userInfo.points,
              }}
            />
            <PersonalInfoItem
              info={{
                itemName: "注册时间",
                itemValue: formatDate(userInfo.registerDate),
              }}
            />
            <PersonalInfoItem
              info={{
                itemName: "上次登录时间",
                itemValue: formatDate(userInfo.lastLoginDate),
              }}
            />
            <div style={{ fontWeight: "100", height: "50px" }}>当前头像</div>
            <Image src={userInfo.avatar} width={100} />
            <br />
            <br />
            <div style={{ fontWeight: "100", height: "50px" }}>上传新头像</div>
            <Upload
              action="/api/upload"
              listType="picture-card"
              accept="image/*"
              maxCount={1}
              onChange={(e) => {
                if (e.file.status === "done") {
                  // 说明上传完毕
                  const url = e.file.response.data;
                  // 处理用户头像的更新
                  handleAvatar(url, "avatar");
                }
              }}
            >
              <PlusOutlined />
            </Upload>
          </Card>
        </div>
        {/* 社交账号 */}
        <div className={styles.row}>
          <Card
            title="社交账号"
            extra={
              <div
                className={styles.edit}
                onClick={() => showModal("社交账号")}
              >
                编辑
              </div>
            }
          >
            <PersonalInfoItem
              info={{
                itemName: "邮箱",
                itemValue: userInfo.mail ? userInfo.mail : "未填写",
              }}
            />
            <PersonalInfoItem
              info={{
                itemName: "QQ号",
                itemValue: userInfo.qq ? userInfo.qq : "未填写",
              }}
            />
            <PersonalInfoItem
              info={{
                itemName: "微信号",
                itemValue: userInfo.wechat ? userInfo.wechat : "未填写",
              }}
            />
            {/* <PersonalInfoItem
              info={{
                itemName: "github",
                itemValue: userInfo.github ? userInfo.github : "未填写",
              }}
            /> */}
          </Card>
        </div>
        {/* 个人简介 */}
        <div className={styles.row}>
          <Card
            title="个人简介"
            extra={
              <div
                className={styles.edit}
                onClick={() => showModal("个人简介")}
              >
                编辑
              </div>
            }
          >
            <p className={styles.intro}>
              {userInfo.intro ? userInfo.intro : "未填写"}
            </p>
          </Card>
        </div>
      </div>

      {/* 修改信息的对话框 */}
      <Modal
        title={panelName}
        open={isModalOpen}
        footer={false}
        onCancel={handleCancel}
      >
        {modalContent}
      </Modal>
    </div>
  );
}

export default Personal;
